package org.moyrax.nereyda.services.errors
{
	import com.adobe.serialization.json.JSON;
	import org.moyrax.nereyda.lib.Base64;
	import org.moyrax.nereyda.services.core.Response;
	import org.moyrax.nereyda.services.template.IServiceResponse;
	
	public dynamic class ServiceError extends Error implements IServiceResponse
	{
		public static const UNKNOWN_ERROR :int = 0xFFFF;
		
		[Bindable] public var line   :int;
		[Bindable] public var source :String;
		[Bindable] public var file   :String;
		[Bindable] public var code   :int = UNKNOWN_ERROR;
		[Bindable] public var trace  :Array;

		private var errorMsg :String = "Error desconocido.";
		private var errorId  :int    = 0;
		
		public function toString():String
		{
			return( super.message );
		}
		
		public function ServiceError( errorMsg:String, errorId:int = 0 ):void
		{
			if ( errorMsg ) {
				this.errorMsg = errorMsg;
			}
			if ( errorId ) {
				this.errorId = errorId; 
			}
			
			super( this.errorMsg, this.errorId );
		}
		
		/**
		 * Toma un objeto Response devuelto por el servicio
		 * y copia las propiedades que correspondan a este
		 * objeto.
		 */
		public function makeFromResponse( response:Response ):void
		{
			if ( !response.error ) {
				return;
			}
			
			response.error = Base64.Decode( response.error );

			var responseError :Response = new Response(response.error);
			
			for ( var item:String in responseError ) {
				this[item] = responseError[item];
			}
		}
	}
}